﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ZL.Web.Utility.Serializer
{
    /// <summary>
    /// .net 自带JsonConvert.SerializeObject功能
    /// </summary>
    public class JsonSerializerHelper
    {
        public static string ToJson(object obj)//将对象转换为Json
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                StringBuilder sb = new StringBuilder();
                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
                return sb.ToString();
            }
        }

        public static T FromJsonTo<T>(string jsonStr)//将Json转换为对象 
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
            T jsonObject = (T)ser.ReadObject(ms);
            ms.Close();
            return jsonObject;
        } 
    }
}